<script setup lang="ts">
import {cloneDeep, initPageQuery, sleep} from "@/utils/common-fn";
import {Ref} from "vue/dist/vue";
import {getUserWeaponByIdApi, getUserWeaponListApi, upUserWeaponApi} from "@/api/sys/dnf/user-weapon";
import {UpWeaponResultVo, UserWeapon} from "@/api/sys/dnf/user-weapon/types";
import {WeaponUp} from "@/api/sys/dnf/weapon-up/types";
import {getWeaponUpNext} from "@/api/sys/dnf/weapon-up";
import {useMoneyStore} from "@/store/views/sys/dnf/money";
import {useUserItemStore} from "@/store/views/sys/dnf/user-item";
import {openConfirm} from "@/components/MyComponent/XMessageBox";
import {useGetOptions} from "@/utils/use/use-get-options";
import {DictType} from "@/utils/enum-type";
import {useMagicKeys} from '@vueuse/core'
import {useSysStore} from "@/store/modules/sys";

const moneyStore = useMoneyStore()
const userItemStore = useUserItemStore()
const {space} = useMagicKeys()
const sysStore = useSysStore()
const {isPhone} = storeToRefs(sysStore)

// 增幅类型
const upType = ref(1)
const total = ref(0)
const loading = ref(false)
let tableData: Ref<UserWeapon[]> = ref([])
const queryData = reactive(initPageQuery<UserWeapon>({
  order: {
    level: 'desc'
  },
  cache: 800,
  relations: {
    weapon: true
  }
}))
let allOptions = useGetOptions(DictType.DnfWeaponType);
const weaponTypeOptions = computed(() => allOptions.value[0])

const initUserWeapon = {
  id: 0,
  level: 0,
  fame: 0,
  num: 0,
  weapon: {id: 0, name: '', level: 0, weaponType: 1, price: 0, priceType: 1}
}
// 选中的武器
const selectedWeapon: Ref<UserWeapon> = ref(cloneDeep(initUserWeapon))
// 下一个等级
const nextWeaponUp: Ref<Partial<WeaponUp>> = ref({})

// 改变增幅类型
function changeUpType(num: number) {
  upType.value = num
}

// 增幅是否高于10
const isGt10 = computed(() => selectedWeapon.value.level >= 10)

// 点击增幅武器
async function handleWeaponUp() {
  if (isGt10.value && !await openConfirm('继续增幅装备会被销毁!是否继续?')) {
    loading.value = false
    return;
  }
  loading.value = true
  await upUserWeaponApi(selectedWeapon.value.id, upType.value).then(async (result: UpWeaponResultVo) => {
    await sleep(isGt10.value ? 2800 : 800)
    if (result.success) {
      ElMessage.success({message: `增幅成功(${result.randomNum})`, duration: isGt10.value ? 3000 : 1000})
    } else {
      if (result.destroy) {
        ElMessage.error({message: `增幅失败,装备已销毁(${result.randomNum})`, duration: 3000})
        selectedWeapon.value.id = 0
      } else {
        ElMessage.warning({message: `增幅失败(${result.randomNum})`, duration: 1500})
      }
    }
  }).finally(() => {
    loading.value = false
    getList()
    moneyStore.getList()
    userItemStore.getList()
    selectWeapon(selectedWeapon.value.id, true)
  })
}

/**
 * 点击武器
 * @param id
 * @param force  是否强制刷新
 */
async function selectWeapon(id: number, force = false) {
  let pass = true
  // 如果正在加载或是点击的是之前的
  if (loading.value || id === selectedWeapon.value.id) {
    pass = false
  }
  if (force) {
    pass = true
  }
  if (!pass) {
    return;
  }
  const userWeapon = await getUserWeaponByIdApi(id)
  if (userWeapon) {
    selectedWeapon.value = userWeapon
    nextWeaponUp.value = await getWeaponUpNext(selectedWeapon.value.weapon.weaponType, selectedWeapon.value.level + 1)
  } else {
    selectedWeapon.value = cloneDeep(initUserWeapon)
  }
}


// 获取列表
async function getList() {
  [tableData.value, total.value] = await getUserWeaponListApi(queryData);
  allOptions = useGetOptions(DictType.DnfWeaponType);
}


watch([() => queryData.pageSize, () => queryData.currentPage], async () => {
  await getList()
})

const uping = ref(false) // 强化中
watch(space, (v) => {
  if (v) {
    if (selectedWeapon.value.id && !uping.value) {
      uping.value = true
      handleWeaponUp().finally(() => {
        uping.value = false
      })
    } else {
    }
  }
})

onMounted(() => {
  getList()
})
</script>

<template>
  <dnf-user-info/>
  <div class="flex" v-if="total > 0">
    <el-row class="w-100%">
      <el-col :xs="24" :sm="selectedWeapon.id ? 12 : 24" :md="selectedWeapon.id ? 15 : 24"
              :lg="selectedWeapon.id ? 17 : 24" :xl="19">
        <x-card class="weapon-card">
          <!--  我的武器        -->
          <div class="main-box" :style="{justifyContent: (isPhone?'space-evenly':'')}">
            <TransitionGroup name="list">
              <div :class="['item',item.id === selectedWeapon.id ? 'selected__item':'']" v-for="item in tableData"
                   :key="item.id"
                   @click="selectWeapon(item.id)">
                <x-image :url="item.weapon?.imageUrl" :size="3"/>
                <span class="weapon-color singe-line">+{{ item.level }} {{ item.weapon?.name }}</span>
                <div class="flex gap-2">
                  <span>武器类别:</span>
                  <x-tag :value="item.weapon?.weaponType" :options="weaponTypeOptions" effect="plain"></x-tag>
                </div>
                <span class="up-color">力量:+{{ item.num }}</span>
                <span class="fame-color">名望:+{{ item.fame }}</span>
              </div>
            </TransitionGroup>
          </div>
          <XPagination
              v-model:page-size="queryData.pageSize"
              v-model:current-page="queryData.currentPage"
              v-model:total="total"
          />
        </x-card>
      </el-col>
      <!-- 强化界面     -->
      <el-col v-if="selectedWeapon.id" :style="{order:(isPhone?-1:1)}"
              :xs="24" :sm="12" :md="9" :lg="7" :xl="5">
        <x-card class="up-card">
          <x-image class="absolute! top-0 left-0" :url="selectedWeapon.weapon?.imageUrl" :size="4.4"/>
          <div class="main-up">
            <el-text class="weapon-color" size="large">+{{ selectedWeapon.level }} {{
                selectedWeapon.weapon.name
              }}
            </el-text>
            <el-text class="line1">
              <span class="up-color">力量:</span>
              <span>+{{ selectedWeapon.num }}</span>
              <span>-></span>
              <span>+{{ nextWeaponUp.num }}</span>
              <span class="add__count">(+{{ nextWeaponUp.num! - selectedWeapon.num }})</span>
            </el-text>
            <el-text class="line2">
              <span>冒险家名望:</span>
              <span>+{{ selectedWeapon.fame }}</span>
              <span>-></span>
              <span>+{{ nextWeaponUp.fame }}</span>
              <span class="add__count">(+{{ nextWeaponUp.fame! - selectedWeapon.fame }})</span>
            </el-text>
            <el-text class="flex gap-4 select-none">
              <div :class="[upType === 1 ? 'select-border' : '','left']" @click="changeUpType(1)">
                <div class="left__title">普通增幅</div>
                <div class="left__content">
                  <div class="left__item">[矛盾的结晶体]{{ nextWeaponUp.maodun }}个</div>
                  <div class="left__item">{{ nextWeaponUp.cost }} 金币</div>
                </div>
              </div>
              <div :class="[upType === 2 ? 'select-border' : '','right']" @click="changeUpType(2)">
                <div class="right__title">增幅器增幅</div>
                <div class="right__content">
                  <div class="right__item">增幅器1个</div>
                </div>
              </div>
            </el-text>
            <el-text size="large">成功率:{{ (nextWeaponUp.percent! / 100).toFixed(2) + '%' }}</el-text>
            <div>
              <el-button type="warning" size="large" class="w-100% border-rd-0" :loading="loading"
                         @click="handleWeaponUp">
                增幅(space)
              </el-button>
            </div>
          </div>
        </x-card>
      </el-col>
    </el-row>
  </div>

</template>

<style scoped lang="scss">
.main-box {
  display: flex;
  flex-wrap: wrap;
  font-weight: bold;
  gap: 1em;
  font-size: 0.9em;
  margin-bottom: 1em;

  .selected__item {
    border: 4px solid rgb(125 136 186 / 40%);
    //box-shadow: 6.4px 5.5px 22.4px rgba(0, 0, 0, 0.161),
    //14px 12px 80px rgba(0, 0, 0, 0.32);
  }
}

.item {
  display: flex;
  justify-content: space-between;
  background-image: linear-gradient(to bottom, #ececeb, #f0ecdc);
  flex-direction: column;
  gap: 0.5em 0;
  height: 13em;
  width: 11em;
  border-radius: 1em;
  padding: 0.8em 0.6em;
  box-shadow: 2px 2px 20px rgba(0, 0, 0, 0.055);

  &:hover {
    cursor: pointer;
    box-shadow: 4px 2.1px 20px rgba(0, 0, 0, 0.15);
  }
}

.weapon-color {
  color: #947c21;
  //text-shadow: 2px 1px 10px #f3cf46;
}

// 力量的颜色
.up-color {
  color: #ab30ac;
}

// 名望的颜色
.fame-color {
  color: #7cb5c0;
}

.main-up {
  display: flex;
  flex-direction: column;
  gap: 1em;

  .line1 {
    display: flex;
    gap: 0 0.4em;
  }

  .line2 {
    color: #7cb5c0;
    display: flex;
    gap: 0 0.4em;
  }
}

.add__count {
  color: #6d9f6e
}

.left, .right {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 0.4em 1em;
  gap: 1em;
  border: 2px solid #e1dfdf;

  &:hover {
    cursor: pointer;
    border: 2px solid #f3d27f;;
  }
}

.select-border {
  border: 2px solid #f3d27f;
}

.left__content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.up-card {
  background-image: linear-gradient(to bottom, #ececeb, #f0ecdc);
}

.weapon-card {
  background-image: linear-gradient(to bottom, #dfdfdc, #fcfcfc);
}

// 动画
.list-move, /* 对移动中的元素应用的过渡 */
.list-enter-active,
.list-leave-active {
  transition: all 1s ease;
}

.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px) rotate(24deg);
}

/* 确保将离开的元素从布局流中删除
  以便能够正确地计算移动的动画。 */
.list-leave-active {
  position: absolute;
}

</style>